package com.zhu.service.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhu.commons.utils.BeanCopyUtils;
import com.zhu.commons.utils.JwtInfo;
import com.zhu.service.admin.pojo.vo.MemberVo;
import com.zhu.service.admin.utils.JwtUtils;
import com.zhu.commons.utils.MailUtils;
import com.zhu.service.admin.pojo.Member;
import com.zhu.service.admin.mapper.MemberMapper;
import com.zhu.service.admin.pojo.vo.LoginVo;
import com.zhu.service.admin.pojo.vo.RegisterVo;
import com.zhu.service.admin.service.IMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author zhu
 * @since 2022-08-17
 */
@Service
@Slf4j
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements IMemberService {
    @Value("${wx.open.appId}")
    private String appId;
    @Value("${wx.open.appSecret}")
    private String appSecret;
    @Value("${wx.open.redirectUri}")
    private String redirectUri;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MemberMapper memberMapper;
    /**
     * 用户注册
     * @param registerVo
     */
    @Override
    public String register(RegisterVo registerVo) {
        String nickName = registerVo.getNickName();
        String password = registerVo.getPassword();
        String email=registerVo.getEmail();
        String code = registerVo.getCode();
        String key="register_"+email;
        if(StringUtils.isEmpty(email)|| !MailUtils.isEmail(email)){
            return "邮箱不合法！";
        }
//        if(StringUtils.isEmpty(password)|| StringUtils.isEmpty(code)||StringUtils.isEmpty(nickName)){
//            return "请输入必填项！";
//        }
        //校验验证码
        String redisCode =(String) redisTemplate.opsForValue().get(key);
        log.info("redisCode======>{},code========>{}",redisCode,code);
        if(!code.equals(redisCode)){
            return "验证码错误！";
        }
        //校验是否已经注册
        LambdaQueryWrapper<Member> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Member::getEmail,email);
        Member member = memberMapper.selectOne(queryWrapper);
        if(member!=null){
            return "您已经注册,不能注册！";
        }
        //密码加密
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
        String newPassword = bCryptPasswordEncoder.encode(password);
        Member newMember = new Member();
        newMember.setEmail(email);
        newMember.setNickname(nickName);
        newMember.setEmail(email);
        newMember.setPassword(newPassword);
        newMember.setAvatar("http://education01bucket.oss-cn-hangzhou.aliyuncs.com/education/2022/08/17/518e6b98-d4fd-4a3c-b975-18577763097e.jpg");
        newMember.setDisabled(false);
        memberMapper.insert(newMember);
        return "注册成功！";


    }

    @Override
    public Map<String,Object> login(LoginVo loginVo)  {
        Map<String,Object> map=new HashMap<>();
        //校验
        String email = loginVo.getEmail();
        String password = loginVo.getPassword();
        if(StringUtils.isEmpty(email)||StringUtils.isEmpty(password)){
           map.put("error","请输入必填项！");
           return map;
        }
        LambdaQueryWrapper<Member> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Member::getEmail,email);
        Member member = memberMapper.selectOne(queryWrapper);
        if(member==null){
            map.put("error","用户名不存在！");
            return map;
        }
        String password1 = member.getPassword();
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();

        if(!bCryptPasswordEncoder.matches(password,password1)){
//            System.out.println(encode+"<---->"+password1);
            map.put("error","密码错误！");
            return map;
        }
        if(member.getDisabled()==true){
            map.put("error","账号被锁定，请联系管理员！");
            return map;
        }

        //登录
        JwtInfo jwtInfo=new JwtInfo();
        jwtInfo.setId(member.getId());
        jwtInfo.setNickname(member.getNickname());
        jwtInfo.setAvatar(member.getAvatar());
        String jwtToken = JwtUtils.getJwtToken(jwtInfo, 18000); //60s*60*5
        map.put("success",jwtToken);
        return map;
    }


    /**
     * 微信登录
     * @return
     */
    @Override
    public String getUrl(HttpSession session) throws UnsupportedEncodingException {
        //组装url：https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=回调地址&response_type=code&scope=snsapi_login&state=随机数#wechat_redirect
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        String encode = URLEncoder.encode(redirectUri, "UTF-8");
        //生成随机数 防止csrf攻击
        String state = UUID.randomUUID().toString();
        session.setAttribute("wx_state",state);
        String wxUrl=String.format(baseUrl,appId,encode,state);
        return wxUrl;
    }

    @Override
    public MemberVo getMember(String memberId) {
        Member member = memberMapper.selectById(memberId);
        MemberVo memberVo = BeanCopyUtils.copyBean(member, MemberVo.class);
        return memberVo;
    }

}
